<?php

namespace app\adminapi\logic;

use app\common\enum\DefaultEnum;
use app\common\model\Device;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * Device逻辑
 * Class DeviceLogic
 * @package app\adminapi\logic
 */
class DeviceLogic extends BaseLogic
{

    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/28 15:43
     */
    public static function add(array $params): bool
    {
        Db::startTrans();
        try {
            Device::create([
                'cid'           => $params['cid'],
                'name'          => $params['name'],
                'device_no'     => $params['device_no'],
                'type'          => $params['type'],
                'status'        => $params['status'] ?? DefaultEnum::SHOW,
                'sort'          => $params['sort'] ?? 1,
            ]);
            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/28 15:43
     */
    public static function edit(array $params): bool
    {
        Db::startTrans();
        try {
            Device::where('id', $params['id'])->update([
                'cid' => $params['cid'],
                'name' => $params['name'],
                'device_no' => $params['device_no'],
                'type' => $params['type'],
                'status'        => $params['status'] ?? DefaultEnum::SHOW,
                'sort'          => $params['sort'] ?? 1,
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2024/02/28 15:43
     */
    public static function delete(array $params): bool
    {
        return Device::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2024/02/28 15:43
     */
    public static function detail($params): array
    {
        return Device::findOrEmpty($params['id'])->toArray();
    }

    public static function updateStatus(array $params)
    {
        Device::update([
            'id' => $params['id'],
            'status' => $params['status']
        ]);
        return true;
    }

}